package com.wukong.logisticsproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wukong.logisticsproject.ex.DeleteException;
import com.wukong.logisticsproject.ex.InsertException;
import com.wukong.logisticsproject.mapper.SysRoleMapper;
import com.wukong.logisticsproject.model.SysRole;
import com.wukong.logisticsproject.model.SysUserRole;
import com.wukong.logisticsproject.mapper.SysUserRoleMapper;
import com.wukong.logisticsproject.service.ISysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author wukong.com
 * @since 2020-10-08
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 获取角色id
     *
     * @param id
     * @return
     */
    public SysUserRole getRoleId(Integer id) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        return userRoleMapper.selectOne(queryWrapper);
    }

    /**
     * 更新用户角色
     *
     * @param userId
     * @param roleId
     * @return
     */
    @Override
    public Integer updateUserIdByRoleId(Integer userId, Integer roleId) {
        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        sysRoleQueryWrapper.eq("role_name", "superadmin");
        SysRole roleNameInfo = sysRoleMapper.selectOne(sysRoleQueryWrapper);
//        QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
//        sysUserRoleQueryWrapper.eq("role_id", roleNameInfo.getRoleId());
//        userRoleMapper.selectList(sysUserRoleQueryWrapper).forEach(sysUserRole -> {
            if (roleNameInfo.getRoleId().equals(roleId) ) {
                throw new InsertException("已有超级管理员，不能添加！！");
            }
//        });
        Integer rows = userRoleMapper.deleteById(userId);

        Integer rows2 = userRoleMapper.addUserByRole(userId, roleId);
        if (rows2 != 1) {
            throw new InsertException("更新用户角色信息失败！！");
        }
        return rows2;
    }
}
